import CellType from "../celltypes";
import {each} from 'lodash';
export default {
    canUndo: true,
    execute: (context, options, isUndo) => {
        try {
            const { sheet, table } = options;
            sheet.suspendPaint();
            const { row: dataRow } = table.dataRange();
            if (isUndo) {
                const { name, row, col, rowCount, colCount, columns, cellTypes, bindingPath, showHeader, rowFilter: { filterButtonVisibleInfo } } = options.old;
                const oldTable = sheet.tables.add(name, row, col, rowCount, colCount, undefined, { showHeader });
                oldTable.filterButtonVisible(false);
                oldTable.bindColumns(columns.map(column => new GC.Spread.Sheets.Tables.TableColumn(column.dataField).name(column.name).dataField(column.dataField)));
                oldTable.bindingPath(bindingPath);
                const FieldCellType = CellType('FieldCellType');
                cellTypes.forEach((cellType, index) => {
                    const cell = sheet.getCell(dataRow, col + index);
                    if (cellType) {
                        cell.cellType(cellType);
                        if (cellType instanceof FieldCellType) {
                            cell.textIndent(2.5)
                                .backgroundImageLayout(GC.Spread.Sheets.ImageLayout.none)
                                .backgroundImage(cellType.getFieldTypeImage());
                        }
                    }
                });
                each(filterButtonVisibleInfo, (value, key) => {
                    oldTable.filterButtonVisible(key, value);
                });
            } else {
                const { col, name, columns, } = table.toJSON();
                const cellTypes = columns.map((d, index) => {
                    return sheet.getCell(dataRow, col + index).cellType();
                })
                options.old = { ...table.toJSON(), cellTypes };
                sheet.tables.remove(name);
                cellTypes.forEach((cellType, index) => {
                    sheet.getCell(dataRow, col + index)
                        .cellType(undefined)
                        .textIndent(0)
                        .backgroundImageLayout(GC.Spread.Sheets.ImageLayout.none)
                        .backgroundImage(undefined);
                });
            }
            sheet.resumePaint();
        } catch (e) {
            if (!!(window.console && window.console.log)) {
                window.console.log(e);
            }
        }
    }

};